<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./lib/bootstrap.css" />
  <script src="./lib/jquery.js"></script>
</head>

<body>
  <!-- 1. 文件选择框 -->
  <input type="file" id="file1" />
  <!-- 2. 上传文件的按钮 -->
  <button id="btnUpload">上传文件</button>

  <!-- bootstrap 中的进度条 -->
  <div class="progress" style="width: 500px; margin: 15px 10px;">
    <div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
      0%
    </div>
  </div>

  <br />
  <!-- 3. img 标签，来显示上传成功以后的图片 -->
  <img src="" alt="" id="img" width="800" />

  <script>
    const btnUpload = document.querySelector('#btnUpload')

    // 2. 为按钮绑定单击事件处理函数
    btnUpload.addEventListener('click', function () {
      // 3. 获取到用户选择的文件列表
      const files = document.querySelector('#file1').files
      // console.dir(document.querySelector('#file1'));
      if (files.length <= 0) {
        return alert('请选择文件')
      }
      const file2 = files[0]
      // console.log(file2);
      const fd = new FormData()
      // 注意：avatar键不是乱写的，参考接口文档

      fd.append('avatar', file2)

      const xhr = new XMLHttpRequest()
      // 监听xhr.upload 的onprogress事件

      xhr.open('POST', 'http://ajax-api.itheima.net/api/file')

      xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
          const percentComplete = Math.ceil((e.loaded / e.total) * 100)
          console.log(percentComplete);
          const percent=document.querySelector('#percent')
          percent.style.width=`${percentComplete}%`
          percent.innerHTML=`${percentComplete}%`
        }
      }

      xhr.upload.onload=function(){
        percent.className='progress-bar progress-bar-success'
      }


      xhr.send(fd)

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          const ele = JSON.parse(xhr.responseText)
          document.querySelector('#img').src = ele.data.url
        }
      }
    })
  </script>
</body>

</html>